import Vue from 'vue'
import upperFirst from 'lodash/upperFirst'
import camelCase from 'lodash/camelCase'
import axios from 'axios'
import { Modal } from 'ant-design-vue'
import { message } from 'ant-design-vue'
import common from '@/global/common.js'
import store from '@/global/store'
import i18n from '@/global/i18n.js'

/* 全局注册组件 */
const requireComponent = require.context(
  // 其组件目录的相对路径
  '../components',
  // 是否查询其子目录
  true,
  // 匹配基础组件文件名的正则表达式
  /[A-Z]\w+\.(vue|js)$/
)

requireComponent.keys().forEach(fileName => {
  // 获取组件配置
  const componentConfig = requireComponent(fileName)

  // 获取组件的 PascalCase 命名
  const componentName = upperFirst(
    camelCase(
      // 获取和目录深度无关的文件名
      fileName
        .split('/')
        .pop()
        .replace(/\.\w+$/, '')
    )
  )

  // 全局注册组件
  Vue.component(
    componentName,
    // 如果这个组件选项是通过 `export default` 导出的，
    // 那么就会优先使用 `.default`，
    // 否则回退到使用模块的根。
    componentConfig.default || componentConfig
  )
})

window.addEventListener('storage', (e) => {
  if (e.key == 'authToken') {
    // 监听方式设置authToken，防止其他tab页登录，本页面不生效
    // This won't work on the same page that is making the changes
    axios.defaults.headers.common['Authorization'] = e.newValue
  }
}, false)

/* axios默认baseURL */
axios.defaults.baseURL = '/api';
axios.defaults.headers.common['Authorization'] = localStorage.getItem("authToken");// 页面刷新时，如果把localStorage里的authToken值取到，免登陆
axios.defaults.headers.common['Accept-Language'] = common.convertLocale(localStorage.getItem("locale"));// 页面刷新时，如果把localStorage里的locale值取到


/* axios异常统一处理*/
// Add a request interceptor
const vue = new Vue({i18n})
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  return config;
}, function (error) {
  console.log("request error:" + error)
  return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use((res) => {
  return res;
}, (error) => {
  let data = error.response.data || {}
  // 跳转到登录页面
  if(error.response.status == 400) {
    let errorCode = data.errorCode || ''
    if (errorCode.endsWith('_me')) { // modal error
      Modal.error({
        zIndex: 1002,
        title: vue.$t('error_message'),
        content: vue.$t(errorCode, data.params),
        okText: vue.$t('modal_ok'),
      })
    } else if (errorCode.endsWith('_mi')) { // modal info
      Modal.info({
        zIndex: 1002,
        title: vue.$t('info_message'),
        content: vue.$t(errorCode, data.params),
        okText: vue.$t('modal_ok'),
      })
    } else if (errorCode.endsWith('_ge')) { // global error
      message.error(vue.$t(errorCode, data.params))
    } else if (errorCode.endsWith('_gi')) { // global info
      message.info(vue.$t(errorCode, data.params))
    } else {
      message.error(vue.$t(errorCode, data.params))
    }
  } else if(error.response.status == 401) {
    let originUrl = error.config.url
    let config = error.response.config || {}
    let params = config.params || {}
    if (params.viewName != 'ROUTER' && !originUrl.includes('/infra/security/logout')) {
      store.commit('openModalLogin')
    }
  } else if(error.response.status == 403) {
    Modal.error({
      zIndex: 1002,
      title: vue.$t('error_message'),
      content: vue.$t('access_forbidden') + error.config.url,
      okText: vue.$t('modal_ok'),
    });
  } else if(error.response.status == 404) {
    Modal.error({
      zIndex: 1002,
      title: vue.$t('error_message'),
      content: vue.$t('not_found') + error.config.url,
      okText: vue.$t('modal_ok'),
    });
  } else {
    console.log(data)
    Modal.error({
      zIndex: 1002,
      title: vue.$t('error_message'),
      content: vue.$t('intenral_server_error'),
      okText: vue.$t('modal_ok'),
    });
  } 
  return Promise.reject(error)
});